<template>
  <div>
    <el-form label-width="80px" :inline="true">
      <el-form-item label="学校名称">
        <el-input
          v-model="search.name"
          placeholder="请输入学校名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="所属地区">
        <el-cascader
          v-model="search.area"
          :options="regions"
          :props="{ checkStrictly: true }"
          placeholder="请选择所属地区"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="覆盖年级">
        <nice-select
          v-model="search.school"
          placeholder="请选择覆盖年级"
          clearable
          :options="selectArr.coverageGrade"
          :multiple="true"
        ></nice-select>
      </el-form-item>
      <el-form-item label="学生规模">
        <nice-select
          v-model="search.studentScale"
          placeholder="请选择学生规模"
          clearable
          :options="selectArr.studentScale"
          labelkey="name"
          valuekey="id"
        ></nice-select>
      </el-form-item>
      <el-form-item label="状态">
        <nice-select
          v-model="search.status"
          placeholder="请选择状态"
          clearable
          :options="statusList"
        ></nice-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" size="small"
          >搜索</el-button
        >
      </el-form-item>
      <div class="right">
        <el-form-item>
          <div class="u-btn-box">
            <!-- <el-button type="primary" @click="handleDistributionSales" size="small">分配销售</el-button>
            <el-button type="primary" @click="handleDistributionOperation" size="small">分配运营</el-button>
            <el-button type="primary" @click="handleBatchOpen" size="small">批量开通</el-button> -->
            <a
              class="button_txt"
              :href="
                'https://jzjx-prod-resource.oss-cn-hangzhou.aliyuncs.com/common/export/school.xlsx?time=' +
                  new Date().getTime()
              "
              download="学校模板下载"
              ><el-button type="primary">下载模板</el-button></a
            >
            <div class="margin-left10 margin-right10">
              <!-- <el-upload
                ref="uploadExl"
                action
                multiple
                :limit="1"
                :http-request="importObj"
                :before-upload="beforeUploadImg"
                :show-file-list="false"
                :file-list="schoolFileList"
              >
                
              </el-upload> -->

              <el-button type="primary" class="u-btn"
                >批量导入<updateFile
                  updata-id="inputName"
                  accpetObj="xls,xlsx,"
                  @updata="file => importObj(file[0].files)"
              /></el-button>
            </div>
            <el-button type="primary" @click="handleAdd('')"
              >新增学校</el-button
            >
          </div>
        </el-form-item>
      </div>
    </el-form>
    <nice-table
      :data="list"
      :columns="columns"
      :pagination="pagination"
      :showSelection="true"
      @handleSelectionChange="handleSelectionChange"
    >
      <el-table-column
        label="操作"
        align="center"
        width="200"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="openHandle(scope.row)"
            :disabled="!!scope.row.isOpen"
            >开通</el-button
          >
          <el-button size="small" type="text" @click="handleAdd(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="text"
            @click="$router.push('/school-banner?id=' + scope.row.id)"
            >banner</el-button
          >
          <el-button
            size="small"
            type="text"
            @click="$router.push('/school-timetable?id=' + scope.row.id)"
            >课表</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <!--新增or编辑-->
    <add-update-school
      v-if="addSchoolDialog"
      ref="addSchool"
      @refreshDataList="onSubmit"
      :options="selectArr"
    ></add-update-school>
    <!--分配销售or分配运营-->
    <sales-operation-allocation
      v-if="salesOperationDialog"
      ref="salesOperation"
      @refreshDataList="onSubmit"
      :mode="mode"
      :multipleSelection="multipleSelection"
    ></sales-operation-allocation>
  </div>
</template>
<script>
// import base from '@/views/base.vue'
import AddUpdateSchool from './add-update-school'
import SalesOperationAllocation from './sales-opreation-allocation'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import { querySchool } from '@/api/user'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
export default {
  name: 'school-list',
  // extends: base,
  data () {
    return {
      schoolFileList: [],
      search: {
        name: '',
        area: [],
        school: [],
        studentScale: '',
        status: 1
      },
      multipleSelection: [],
      selectArr: {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      },
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCurrentChange,
        handleSizeChange: this.handleSizeChange
      },
      statusList: [
        { label: '已开通', value: 1 },
        { label: '未开通', value: 0 }
      ],
      total: 0,
      mode: '',
      addSchoolDialog: false,
      salesOperationDialog: false,
      list: [],
      columns: [
        {
          label: 'ID',
          prop: 'id'
        },
        {
          label: '学校名称',
          prop: 'schoolName',
          width: '200',
          extends: [
            {
              clickFunction: val => {
                this.viewSchool(val)
              }
            }
          ]
        },
        {
          label: '所属地区',
          prop: 'region',
          width: '200'
        },
        {
          label: '学校性质',
          prop: 'schoolType',
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(val, this.selectArr.schoolType)
              }
            }
          ]
        },
        {
          label: '等级',
          prop: 'level',
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(val, this.selectArr.level)
              }
            }
          ]
        },
        {
          label: '覆盖年级',
          prop: 'coverageGrade'
        },
        {
          label: '状态',
          prop: 'isOpen',
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(val, this.statusList)
              }
            }
          ]
        }
      ]
    }
  },
  activated () {
    this.$store.dispatch('common/saveRegion')
    this.search.area = []
    this.search.area[0] = ''
    this.getDataList('', '', '', '')
    this.queyEnumByTableName()
  },
  computed: {
    regions () {
      return this.$store.state.common.regions
    }
  },
  components: {
    AddUpdateSchool,
    SalesOperationAllocation,
    updateFile: resolve => require(['@/components/updateFile.vue'], resolve)
  },
  methods: {
    async getDataList (nurseryGrade, juniorGrade, middleGrade, highGrade) {
      let res = await adminschoollist({
        schoolName: this.search.name,
        studentScale: this.search.studentScale,
        province: this.search.area[0] || '',
        city: this.search.area[1] || '',
        area: this.search.area[2] || '',
        openStatus: this.search.status,
        pageSize: this.pagination.pageSize,
        currPage: this.pagination.pageNum
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        if (data.data) {
          this.pagination.total = data.data.totalCount
          this.list = data.data.list
          console.log(data.data)
          if (this.list && this.list.length) {
            this.list.forEach(ele => {
              ele.region = ele.provinceName + ele.cityName + ele.areaName
              ele.isOpen = ele.isOpen || 0
              let coverageGrade = []
              ele.nurseryGrade && coverageGrade.push('幼儿园')
              ele.juniorGrade && coverageGrade.push('小学')
              ele.middleGrade && coverageGrade.push('初中')
              ele.highGrade && coverageGrade.push('高中')
              if (coverageGrade && coverageGrade.length) {
                ele.coverageGrade = coverageGrade.join(',')
              } else {
                ele.coverageGrade = ''
              }
            })
          }
        }
      }
    },
    // 获取枚举
    async queyEnumByTableName () {
      // 获取学校的枚举接口
      let selectArr = {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      }
      let enumschoolallRes = await enumschoolall({})
      if (enumschoolallRes[0]) {
        return
      }
      this.selectArr = enumschoolallRes[1].data
      this.selectArr.level = [
        {
          label: 'A',
          value: 1
        },
        {
          label: 'B',
          value: 2
        },
        {
          label: 'C',
          value: 3
        }
      ]
      this.selectArr.coverageGrade = [
        {
          label: '幼儿园',
          value: 1
        },
        {
          label: '小学',
          value: 2
        },
        {
          label: '初中',
          value: 3
        },
        {
          label: '高中',
          value: 4
        }
      ]
    },
    onSubmit () {
      this.pagination.pageNum = 1
      if (this.search.school && this.search.school.length) {
        this.getInit()
      } else {
        this.getDataList('', '', '', '')
      }
    },
    getInit () {
      let nurseryGrade = 0,
        juniorGrade = 0,
        middleGrade = 0,
        highGrade = 0
      this.selectArr.coverageGrade.forEach(item => {
        this.search.school.forEach(ele => {
          if (ele === item.value) {
            if (item.label === '幼儿园') {
              nurseryGrade = 1
            } else if (item.label === '小学') {
              juniorGrade = 1
            } else if (item.label === '初中') {
              middleGrade = 1
            } else if (item.label === '高中') {
              highGrade = 1
            }
          }
        })
      })
      this.getDataList(nurseryGrade, juniorGrade, middleGrade, highGrade)
    },
    // 批量导入
    async importObj (file) {
      let formData = new FormData()
      formData.append('file', file)
      let res = await adminimportschoolExport(formData)
      if (res[0]) {
        return
      }
      this.getDataList('', '', '', '')
      // this.$ref.uploadExl.clearFiles();
      this.schoolFileList = []
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt100M = file.size / 1024 / 1024 < 200
      if (!isExcel) {
        this.$message.error('上传的文件只能是 xls 或 xlsx 格式!')
      }
      if (!isLt100M) {
        this.$message.error('上传的文件大小不能超过 200MB!')
      }
      return isExcel && isLt100M
    },
    handleCurrentChange (val) {
      this.pagination.pageNum = val
      if (this.search.school && this.search.school.length) {
        this.getInit()
      } else {
        this.getDataList('', '', '', '')
      }
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      if (this.search.school && this.search.school.length) {
        this.getInit()
      } else {
        this.getDataList('', '', '', '')
      }
    },
    handleDistributionSales () {
      if (!this.multipleSelection.length) {
        this.$alert('请选择需要批量分配销售的学校', '提示', {
          confirmButtonText: '关闭',
          callback: action => {}
        })
      } else {
        this.mode = 'sales'
        this.salesOperationInit()
      }
    },
    handleDistributionOperation () {
      if (!this.multipleSelection.length) {
        this.$alert('请选择需要批量分配运营的学校', '提示', {
          confirmButtonText: '关闭',
          callback: action => {}
        })
      } else {
        this.mode = 'operation'
        this.salesOperationInit()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    salesOperationInit () {
      this.salesOperationDialog = true
      this.$nextTick(() => {
        this.$refs.salesOperation.init()
      })
    },
    handleBatchOpen () {
      if (!this.multipleSelection.length) {
        this.$alert('请选择需要批量开通的学校', '提示', {
          confirmButtonText: '关闭',
          callback: action => {}
        })
      } else {
        this.$confirm('确定进行批量开通操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.schoolOpen()
          })
          .catch(() => {})
      }
    },
    async downHandle () {
      let res = await downloadTemplateFile({
        data: [
          {
            header: '学校名称(必填)',
            tableandfield: 'nice_school.school_name'
          },
          { header: '所属地区(必填)', tableandfield: 'nice_school.address' },
          { header: '学校性质', tableandfield: 'nice_school.schoolType' },
          {
            header: '幼儿园覆盖(1是0否)',
            tableandfield: 'nice_school.nursery_grade'
          },
          {
            header: '小学覆盖年级(1是0否)',
            tableandfield: 'nice_school.junior_grade'
          },
          {
            header: '初中覆盖年级(1是0否)',
            tableandfield: 'nice_school.middle_grade'
          },
          {
            header: '高中覆盖年级(1是0否)',
            tableandfield: 'nice_school.high_grade'
          },
          { header: '学校规模', tableandfield: 'nice_school.studentScale' }
        ]
      })
      if (res.status === 200) {
        let filename = decodeURI('学校模板下载.xls')
        filename = filename.replace(/\"/g, '')
        this.$downloadExcel(res.data, filename)
      }
    },
    handleAdd (obj) {
      this.addSchoolDialog = false
      this.$nextTick(() => {
        this.addSchoolDialog = true
        this.$nextTick(() => {
          if (obj) {
            obj = JSON.parse(JSON.stringify(obj))
            obj.areaAll = [
              Number(obj.province),
              Number(obj.city),
              Number(obj.area)
            ]

            let coverageGrade = []
            obj.nurseryGrade && coverageGrade.push(1)
            obj.juniorGrade && coverageGrade.push(2)
            obj.middleGrade && coverageGrade.push(3)
            obj.highGrade && coverageGrade.push(4)
            if (coverageGrade && coverageGrade.length) {
              obj.coverageGrade = coverageGrade
            } else {
              obj.coverageGrade = []
            }
            this.$refs.addSchool.schoolForm = obj
          } else {
            obj = {
              schoolName: '',
              areaAll: [],
              schoolType: '',
              coverageGrade: [],
              studentScale: '',
              schoolMaster: ''
            }
          }
          this.$refs.addSchool.init(obj.id ? obj : '')
        })
      })
    },
    openHandle (row) {
      this.$confirm('确定进行开通操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.schoolOpen(row.id)
        })
        .catch(() => {})
    },
    async schoolOpen (id) {
      let res = id
        ? await tableUpdate([
          {
            table_name: 'nice_school',
            update: [{ is_open: '1' }],
            where: [{ id: id }]
          }
        ])
        : await tableUpdate(
            this.multipleSelection.map(ele => {
              return {
                table_name: 'nice_school',
                update: [{ isOpen: '1' }],
                where: [{ id: ele.id }]
              }
            })
          )
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message.success(id ? '开通成功！' : '批量开通成功！')
        if (this.search.school && this.search.school.length) {
          this.getInit()
        } else {
          this.getDataList('', '', '', '')
        }
      } else {
        this.$message.error(data.msg)
      }
    },
    handleDelete (row) {
      this.$confirm('确定进行删除操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteSchool(row)
        })
        .catch(() => {})
    },
    async deleteSchool (row) {
      let res = await tableUpdate([
        {
          table_name: 'nice_school',
          update: [
            {
              enable: 1
            }
          ],
          where: [
            {
              id: row.id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message.success('删除学校成功！')
        if (this.search.school && this.search.school.length) {
          this.getInit()
        } else {
          this.getDataList('', '', '', '')
        }
      }
    },
    viewSchool (row) {
      this.$router.push({
        name: 'school-detail',
        params: { id: row.id }
      })
    }
  }
}
</script>
<style scoped>
.u-btn-box {
  display: flex;
}
.u-btn {
  font-size: 12px;
  position: relative;
}
</style>
